package com.finance.services.dao;

import com.finance.services.util.Util;
import java.lang.reflect.ParameterizedType;
import javax.inject.Inject;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

/**
 *
 * @author Administrator
 * @param <T>
 */
public abstract class AbstractDAO<T extends Object> {

    @Inject
    private SessionFactory factory;
    private Class<T> domainClass;

    @Inject
    protected Util util;

    protected Session getSession() {
        return factory.getCurrentSession();
    }

    private Class<T> getDomainClass() {
        if (domainClass == null) {
            ParameterizedType thisType = (ParameterizedType) getClass().getGenericSuperclass();
            this.domainClass = (Class<T>) thisType.getActualTypeArguments()[0];
        }
        return domainClass;
    }

    private String getDomainClassName() {
        return getDomainClass().getSimpleName();
    }

    protected long generateId() {
        return (long) getSession().createQuery("SELECT COALESCE( MAX(e.id), 0) + 1 FROM " + getDomainClassName() + " e").uniqueResult();
    }
}
